﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Policy;
using System.Globalization;

namespace WinNMPForms
{
    internal class PhpCgi
    {
        // nginx 所在目录
        private static readonly string exeName = "php-cgi";
        private string appDir;
        private string path;
        private string version;
        private bool isExits = false;
        private bool isRun = false;
        public string AppDir { get => appDir; set => appDir = value; }
        public string Version { get => version; set => version = value; }
        public string Path { get => path; set => path = value; }
        public bool IsRun { get => isRun; set => isRun = value; }
        public bool IsExits { get => isExits; set => isExits = value; }

        public PhpCgi()
        {
            appDir = ConfigurationManager.AppSettings.Get("php_dir").Replace("/", "\\");

            if (appDir.Substring(appDir.Length - 1, 1).Equals("\\") == false)
            {
                appDir += "\\";
            }

            path = appDir + "php.exe";

            if (File.Exists(path) != false)
            {
                isExits = true;

                string ver = ShowVersion();

                if (ver != null && ver != "")
                {
                    version = ver.Replace("\r\n", "\n").Split('\n')[0].Split(' ')[1];
                }

                Process[] myProcess = Process.GetProcessesByName(exeName);

                if (myProcess.Length > 0)
                {
                    isRun = true;
                }
            }
        }

        public void Start()
        {
            ProcessRun.NoWaitExitStartCmd(this.appDir, exeName, @"-b 127.0.0.1:9000 -c .\php.ini");
           
            isRun = true;
        }

        public void Stop()
        {
            ProcessRun.ProcessStop(exeName);

            isRun = false;
        }
        
        public string ShowVersion()
        {
            // nginx 控制台输出用的是 tandardOutput
            (string so, _) = ProcessRun.ProcessStart(this.path, @"-v");

            return so;
        }
    }
}
